package com.zt.questionnaire.common.typehandler;

import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Set;

public  class EntityJsonSetTypeHandler extends BaseTypeHandler<Set> {

	private String toJson(Set set) {
		try {
			return JSONObject.toJSONString(set);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	private Set toObject(String content) {
		if (content != null && !content.isEmpty()) {
			try {
//				return JSONObject.parseObject(content, Set.class);
				return JSONObject.parseObject(content,Set.class);
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		} else {
			return null;
		}
	}

	@Override
	public Set getNullableResult(ResultSet rs, String arg1) throws SQLException {
		// TODO Auto-generated method stub
		return this.toObject(rs.getString(arg1));
	}

	@Override
	public Set getNullableResult(ResultSet rs, int arg1) throws SQLException {
		// TODO Auto-generated method stub
		return this.toObject(rs.getString(arg1));
	}

	@Override
	public Set getNullableResult(CallableStatement cs, int arg1) throws SQLException {
		// TODO Auto-generated method stub
		return this.toObject(cs.getString(arg1));
	}

	@Override
	public void setNonNullParameter(PreparedStatement ps, int arg1, Set arg2, JdbcType arg3) throws SQLException {
		ps.setString(arg1, this.toJson(arg2));
	}

}
